<template>
  <div>
    <x-header :left-options="{backText: ''}" @on-click-more="showMenus = true" >选择题型</x-header>
    <div class="ui-body" id="uploadImg">
      <div>
        <div style="min-height: 300px;position: relative;overflow: hidden;">
          <span v-if="!titlePath" style="color: #999;position: absolute;top:50%;left: 50%;-webkit-transform: translate(-50%, -50%);transform: translate(-50%, -50%);">点击添加图</span>
          <input type="file" accept="image/*" ref="titleImg" style="position: absolute;width:100%;height: 100%;top:0;opacity: 0;z-index: 999;"> 
          <img v-if="titlePath" :src="titlePath" style="width: 100%;display: block;position: absolute;top: 50%;-webkit-transform: translateY(-50%);transform: translateY(-50%);"></img>
          <div style="z-index:999;white-space:nowrap;overflow: hidden;text-overflow: ellipsis;background-color:rgba(0,0,0,0.6);color: white;text-align: center;line-height: 40px;font-size: 18px;position: absolute;bottom: 0;width: 100%;" @click="$router.go(-1)">{{$store.state.title}}</div>
        </div>
        <group gutter="0">
          <ul class="ui-some-info">
            <li><i></i>{{lastTime}}</li>
            <li><i></i>{{$store.state.TakeInNumber}}</li>
            <li style="display: none;"><i></i>0</li>
            <li><i></i>{{EmployeeName}}</li>
          </ul>
        </group>
        <div  style="background-color: white;margin-top: 20px;">
          <div v-for="(item, index) in $store.state.descList" style="padding: 10px 20px;">
            <div v-if="item.text" class="ui-show-desc">
                {{item.text}}
              </div>
              <img v-if="item.img" :src="item.img" style="width: 60%;margin: 0 auto; display: block;"> 
          </div>
        </div>
        <group title='添加问题'>
          <ul>
            <li class="ui-answer-list"><i class="ui-add-question" @click="showOp(0)"></i></li>
            <li class="ui-answer-list" v-for="(item, index) in $store.state.questionList">
              <group gutter=0><cell :title="(index + 1) + '.  ' +  item.question" is-link @click.native="editQuestion(index, item.type)"></cell></group>
              <i class="ui-add-question" @click="showOp(index+1)"></i>
            </li>
          </ul>
        </group>
        <actionsheet v-model="show" :menus="menus" :close-on-clicking-mask="false" show-cancel @on-click-menu-one="operation('one')" @on-click-menu-more="operation('more')" ></actionsheet>
        
        
        <box gap="10px 10px">
          <flexbox>
            <flexbox-item>
              <x-button type="primary" @click.native="saveAndShow(false)" style="margin-top: 40px;">保存</x-button>
            </flexbox-item>
            <flexbox-item> 
              <x-button  type="primary" @click.native="saveAndShow(true)" style="margin-top: 40px;">保存并预览</x-button>
            </flexbox-item>
          </flexbox>
          <x-button  type="primary" link="BACK" style="margin-top: 20px;">上一步</x-button>
        </box>
      </div>
    </div>
  </div>
</template>

<script>
import { Group, Cell, XTextarea, XImg, XButton, Box, XHeader, Flexbox, FlexboxItem, Actionsheet, dateFormat } from 'vux'
import store from '@/store'
import axios from 'axios'
require('es6-promise').polyfill()
import weui from '../../static/weui.min.js'
var qs = require('qs')

export default {
  store,
  components: {
    Group,
    Cell,
    XTextarea,
    XImg,
    XButton,
    Box,
    Flexbox,
    FlexboxItem,
    XHeader,
    Actionsheet
  },
  data () {
    return {
      show: false,
      titlePath: this.$store.state.titlePath,
      readonly: true,
      index: 0,
      lastTime: '',
      EmployeeName: '',
      menus: {
        one: '单选题',
        more: '多选题'
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next((vm) => {
      if (from.params.create) {
        vm.reset()
      }
    })
  },
  mounted () {
    this.initUpload()
    this.EmployeeName = document.getElementById('EmployeeName').value
    var arr = dateFormat(this.$store.state.endTime, 'YYYY MM DD').split(' ')
    let t = (new Date(arr[0], arr[1] - 1, arr[2]).getTime() - new Date().getTime()) / 1000
    this.lastTime = parseInt(t / 86400) + '天' + parseInt(t % 86400 / 3600) + '小时' + parseInt(t % 86400 % 3600 / 60) + '分'
  },
  methods: {
    initUpload () {
      let _this = this
      weui.uploader('#uploadImg', {
        url: _this.$store.state.url + '/VoteManage/VoteImageUpload.ashx',
        auto: true,
        type: 'base64',
        fileVal: 'uploadImg',
        compress: {
          quality: 0.5
        },
        onBeforeQueued: function (files) {
          _this.$vux.loading.show({
            text: '上传中...'
          })
          if (['image/jpg', 'image/jpeg', 'image/png', 'image/gif'].indexOf(this.type) < 0) {
            _this.$vux.toast.text('请上传图片', 'bottom')
            _this.$vux.loading.hide()
            return false
          }
        },
        onQueued: function () {
          _this.upLoadImg(this.base64)
        },
        onBeforeSend: function (data, headers) {
          return false // 阻止文件上传
        }
      })
    },
    reset () {
      this.$store.state.questionList = []
    },
    operation (key) {
      this.$router.push({name: 'Question', params: {type: key, index: this.index, edit: false}})
    },
    showOp (index) {
      this.show = !this.show
      this.index = index
    },
    editQuestion (index, type) {
      this.$router.push({name: 'Question', params: {index: index, edit: true, type: type}})
    },
    saveAndShow (flag) {
      if (!this.titlePath) {
        this.$vux.toast.text('请添加图片', 'bottom')
        return
      }
      if (this.$store.state.questionList.length === 0) {
        this.$vux.toast.text('请添加问题', 'bottom')
        return
      }
      this.$vux.loading.show({
        text: '正在保存...'
      })
      this.saveData(flag)
    },
    saveData (flag) {
      let votequestions = []
      let questionList = this.$store.state.questionList
      for (let i in questionList) {
        let voteoptions = []
        for (let j in questionList[i].answerList) {
          let answer = questionList[i].answerList[j]
          let voteoption = {
            OptionName: answer.title,
            OptionImgUrl: '',
            Order: (Number(j) + 1),
            IsCheck: false,
            byb: null,
            ImgUrlList: null,
            ImgList: [...answer.img]
          }
          voteoptions.splice(j, 0, voteoption)
        }
        let votequestion = {
          VoteQuestionName: questionList[i].question,
          ImageUrl: questionList[i].questionImg,
          State: true,
          MaxSelected: Number(questionList[i].MaxSelected),
          Order: (Number(i) + 1),
          VoteQuestionType: questionList[i].type === 'one' ? 0 : 1,
          voteoptions: voteoptions
        }
        votequestions.splice(i, 0, votequestion)
      }
      let json = {
        ID: this.$store.state.id,
        VoteTheme: this.$store.state.title,
        EndDate: dateFormat(this.$store.state.endTime, 'YYYY-MM-DD'),
        VoteName: JSON.stringify({descList: this.$store.state.descList}),
        VoteRange: 0,
        EndState: '',
        VoteCount: 1,
        RrsultShowType: this.$store.state.tSet[0] === '投票前' ? 0 : 1,
        EndTest: '',
        IsAnonymous: true,
        PaperSkin: '',
        Creater: document.getElementById('Creater').value,
        CreateTime: dateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss'),
        EnterpriseID: document.getElementById('EnterpriseID').value,
        FengMian: this.$store.state.titlePath,
        votequestions: votequestions
      }
      axios.post(this.$store.state.url + '/VoteManage/VoteService.ashx', qs.stringify({JsonString: JSON.stringify(json)}))
      .then((rs) => {
        let data = rs.data
        if (data.status === 200) {
          this.$store.commit('reset')
          if (flag) {
            this.$router.push({name: 'Show', params: {id: data.message}})
          } else {
            this.$router.push({name: 'Index'})
          }
        } else {
          this.$vux.toast.text(data.msg, 'bottom')
        }
        this.$vux.loading.hide()
      })
      .catch((response) => {
        this.$vux.toast.text('请求失败请稍后再试', 'bottom')
      })
    },
    showLoading () {
      this.$vux.loading.show({
        text: '上传中...'
      })
    },
    getObjectURL (file) {
      try {
        this.showLoading()
        var url = null
        var _this = this
        if (window.createObjectURL !== undefined) { // basic
          url = window.createObjectURL(file)
        } else if (window.URL !== undefined) { // mozilla(firefox)
          url = window.URL.createObjectURL(file)
        } else if (window.webkitURL !== undefined) { // webkit or chrome
          url = window.webkitURL.createObjectURL(file)
        }
        var Img = new Image()
        Img.src = url
        Img.onload = function () { // 要先确保图片完整获取到，这是个异步事件
          let canvas = document.createElement('canvas')
          let width = Img.width
          let height = Img.height
          canvas.width = width
          canvas.height = height
          canvas.getContext('2d').drawImage(Img, 0, 0, width, height) // 将图片绘制到canvas中
          _this.titlePath = canvas.toDataURL('image/jpeg')
          _this.upLoadImg(canvas.toDataURL('image/jpeg'))
        }
      } catch (e) {
        this.$vux.toast.text('该设备不支持拍照上传', 'bottom')
      }
    },
    getBase64Image (e) {
      try {
        var files = e.target.files || e.dataTransfer.files
        if (!files.length) return
        var _this = this
        if (JSON.stringify(files[0]).length === 2) {
          this.getObjectURL(files[0])
          return
        }
        this.showLoading()
        var file = files[0]
        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function (e) {
          _this.upLoadImg(this.result)
        }
      } catch (e) {
        this.$vux.toast.text('该设备不支持拍照上传', 'bottom')
      }
    },
    upLoadImg (Base64) {
      let _this = this
      axios.post(this.$store.state.url + '/VoteManage/VoteImageUpload.ashx', qs.stringify({Base64: Base64}))
      .then((rs) => {
        let data = rs.data
        if (data.code === 200) {
          _this.titlePath = _this.$store.state.imgUrl + data.url
          _this.$store.commit('updateState', {key: 'titlePath', value: _this.titlePath})
          _this.$vux.loading.hide()
        } else {
          this.$vux.toast.text(data.msg, 'bottom')
        }
        _this.$vux.loading.hide()
      })
      .catch((response) => {
        this.$vux.toast.text('请求失败请稍后再试', 'bottom')
      })
    }
  }
}
</script>

<style scoped src='@/assets/css/edit-two.css'></style>
